#coding:utf8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from review.mysqlhandler import dbh
import datetime


def index(request,offset):
	rev = Rate(offset)
	cpmc = rev.retCPMC()
	ratelist = rev.retRate()
	return render_to_response('rate.html',{'cpid':offset,'cpmc':cpmc[0][0],'ratelist':ratelist})

def add(request):
	cpid = request.GET.get('cpid',None)
	tucao = request.GET.get('tucao',None)
	info = request.GET.get('info',None)
	msg = ''# 响应给前端ajax请求的信息
	try:
		newid = None # 新增评论的编号
		rev = Rate(cpid)
		maxid = rev.retMaxID()[0][0] # 评论编号后4位尾号
		if maxid:
			newid = datetime.datetime.now().strftime('%Y%m%d') + str(int(maxid)+1).zfill(4)
		else:
			newid = datetime.datetime.now().strftime('%Y%m%d') + '0001'

		if newid:
			sqlAddRate = '''
				INSERT INTO T_RATE VALUES('%s',NOW(),'%s','%s','%s');
			''' % (newid,cpid,tucao,info)
			dbh.ExecNonQuery(sqlAddRate)
	except:
		msg = 'failed'

	return HttpResponse(msg)

class Rate(object):
	"""docstring for Rate"""
	dataNow = datetime.datetime.now().strftime('%Y-%m-%d') # 获取当前日期并转为字符型

	def __init__(self, cpid):
		self.cpid = cpid

	def retCPMC(self):
		sqlCPMC = '''
			SELECT B.CPMC FROM T_MENU A
			LEFT JOIN (
				SELECT B.FL_ID,B.FLMC,A.CP_ID,A.CPMC FROM T_CP A
				LEFT JOIN T_FL B ON A.FL_ID = B.FL_ID
			) B ON A.CP_ID = B.CP_ID
			WHERE A.RQ = '%s' AND A.CP_ID = '%s';
		''' % (self.dataNow, self.cpid)
		return dbh.ExecQuery(sqlCPMC)

	def retRate(self):
		sqlRate = '''
			SELECT REVIEW FROM T_RATE
			WHERE DATE_FORMAT(RQ,'%%Y-%%m-%%d') = '%s' 
				AND CP_ID = '%s';
		''' % (self.dataNow, self.cpid)
		return dbh.ExecQuery(sqlRate)
	
	# 
	# 返回当天该菜品的最后一个评论的编号末4位，如果当天对该菜品无评论则返回None
	# 
	def retMaxID(self):
		sqlMaxID = '''
			SELECT RIGHT(MAX(RATE_ID),4) FROM T_RATE
			WHERE DATE_FORMAT(RQ,'%%Y-%%m-%%d') = '%s';
		''' % self.dataNow
		return dbh.ExecQuery(sqlMaxID)